<template>
  <div id="qcInstrItemRuleDiv">
    <Breadcrumb content="质控规则设定" />
    <div class="bodyContent">
      <Splitpanes>
        <Pane size="20">
          <vxe-toolbar perfect>
            <template #buttons>
              <div class="smallToolTitle">仪器</div>
              <vxe-select v-model="searchForm.instrIds" multiple :filterable="true" clearable @change="valueChangeEvent">
                <vxe-option v-for="instr in instrList" :key="instr.id" :value="instr.id" :label="instr.instrName"></vxe-option>
              </vxe-select>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="treeLoading" @click="findInstrItemTree"></vxe-button>
            </template>
          </vxe-toolbar>
          <el-scrollbar style="height: calc(100% - 40px)">
            <div class="sampleType">
              <el-scrollbar>
                <el-tree :expand-on-click-node="false" :default-expanded-keys="expandedkeys" :data="instrItemTree" :props="defaultProps" node-key="id" ref="dataTreeRef" highlight-current class="tools-tree" @node-click="handleClickType" v-loading="treeLoading">
                  <template #default="{ data, node }">
                    <div style="float: right">
                      <img :src="`${getAssetsFile('images/qc/' + data.type + '.png')}`" style="width: 15px; height: 15px; margin-right: 10px" />
                      {{ data.name }}
                    </div>
                  </template>
                </el-tree>
              </el-scrollbar>
            </div>
          </el-scrollbar>
        </Pane>
        <Pane size="80">
          <vxe-toolbar perfect>
            <template #buttons>
              <div class="smallToolTitle">质控规则设定</div>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="rloading" :disabled="disabledTag" @click="findInstrItemRuleList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新增" :disabled="disabledTag" @click="addInstrItemRule"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" :disabled="disabledTag" @click="saveInstrItemRuleList"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" :disabled="disabledTag" @click="deleteInstrItemRule"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="tableBox">
            <vxe-table ref="instrItemRuleTableRef" @current-change="ruleRowClick" class="mytable-scrollbar" border="inner" align="center" height="auto" :row-config="{ isCurrent: true, isHover: true }" :data="instrItemRuleList" :loading="rloading" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }" resizable show-overflow keep-source>
              <vxe-column type="checkbox" width="30" align="center"></vxe-column>

              <vxe-column field="ruleType" title="规则大类" width="150" :edit-render="{}">
                <template #default="{ row }">
                  <span>{{ formatRuleType(row) }}</span>
                </template>
                <template #edit="{ row }">
                  <vxe-select v-model="row.ruleType" placeholder="可清除" clearable>
                    <vxe-option v-for="selectDetail in qcRuleTypeList" :key="selectDetail.code" :value="selectDetail.code" :label="selectDetail.name"></vxe-option>
                  </vxe-select>
                </template>
              </vxe-column>

              <vxe-column field="ruleIds" title="质控规则" width="550" :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #default="{ row }">
                  <span>{{ formatRuleNameByIds(row) }}</span>
                </template>
                <!-- { field: '', title: '', type: 'checkbox', width: '30px' }, -->
                <template #edit="{ rowIndex }">
                  <SelectDataCheckedList :url="'/api/qc/qcRule/findQcRuleList'" ref="ruleSelectListRef" :column="[
                      { field: 'code', title: '编号' }, //列标题
                      { field: 'name', title: '名称' }
                    ]" :searchParam="{}" :isPage="false" @SelectCellClick="
                      (e) => {
                        selectRow(e, rowIndex);
                      }
                    " :clickRowId="sltInstrItemRule.ruleIds"></SelectDataCheckedList>
                </template>
              </vxe-column>
              <vxe-column field="isAlarm" title="是否警告" width="100" :edit-render="{}">
                <template #default="{ row }">
                  <el-tag :type="row.isAlarm ? 'success' : 'danger'">
                    {{ row.isAlarm ? '是' : '否' }}
                  </el-tag>
                </template>
                <template #edit="{ row }">
                  <vxe-switch v-model="row.isAlarm" open-label="是" close-label="否"></vxe-switch>
                </template>
              </vxe-column>
              <vxe-column field="isOutControl" title="是否失控" width="100" :edit-render="{}">
                <template #default="{ row }">
                  <el-tag :type="row.isOutControl ? 'success' : 'danger'">{{ row.isOutControl ? '是' : '否' }}
                  </el-tag>
                </template>
                <template #edit="{ row }">
                  <vxe-switch v-model="row.isOutControl" open-label="是" close-label="否"></vxe-switch>
                </template>
              </vxe-column>

              <vxe-column field="enableDate" title="启用日期" width="150" :edit-render="{}">
                <template #edit="{ row, rowIndex, column }">
                  <vxe-input v-model="row.enableDate" placeholder="日期选择" type="date"></vxe-input>
                </template>
              </vxe-column>

              <vxe-column field="stopDate" title="停用日期" width="150" :edit-render="{}">
                <template #edit="{ row, rowIndex, column }">
                  <vxe-input v-model="row.stopDate" placeholder="日期选择" type="date" clearable></vxe-input>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import moment from 'moment';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示
import { getAssetsFile } from '@/utils/common';
import { isEmpty } from 'lodash';
import SelectDataCheckedList from '@/components/SelectMultDataGrid.vue';
import SelectDataGrid from '@/components/SelectDataGrid.vue';
import { log } from 'console';

// 全局变量区 =============
let instrItemTree: any = reactive([]); //左侧仪器表格数据
let instrItemRuleList: any = reactive([]);
let sltInstrItem: any = reactive({});
let sltInstrItemRule: any = {};
let treeLoading = ref(false);
let rloading = ref(false);
let disabledTag = ref(true); //中间质控品维护按钮标记
let qcRuleTypeList: any = reactive([]); //选择字典
let qcRuleList: any = reactive([]);
let ruleSelectListRef = ref(null);
let instrList: any = reactive([]); //左侧仪器下拉项
let expandedkeys: any = reactive([]);

let searchForm = ref({
  searchValue: '',
  instrId: '',
  instrIds: []
});
// 最左侧的树
let defaultProps = {
  children: 'children',
  label: 'name'
};
// 方法定义区 =============
// 页面加载时更新列表(左侧)
onMounted(() => {
  findInstrSetupList();
  findInstrItemTree(); // 获取左侧仪器表格数据
  getDictItemsList(); //批量获取字典
  getQcRuleList();
});

// 获取左侧仪器下拉选项数据(标题)
function findInstrSetupList() {
  instrList.length = 0; //放入数据前清空数据
  const url = '/lis/instrSetup/getInstrSetupList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { seachValue: '', poct: 1 }
    })
    .then((res: any) => {
      instrList.push(...res.data);
    })
    .catch((err: any) => {
      VxeMessage('获取左侧仪器表格数据异常', VxeNotifyType.error);
    });
}

// 仪器下拉选择 改变
function valueChangeEvent() {
  findInstrItemTree();
}
//批量获取字典
async function getDictItemsList() {
  let dictTreeTypeCodes: any = ['QCRuleType'];

  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const qcRuleType = dictTreeTypeItems.data.find((item) => item.code === 'QCRuleType');
  qcRuleTypeList.push(...qcRuleType.detailDataList);
}
async function getQcRuleList() {
  const url = '/api/qc/qcRule/findQcRuleList';
  const data = await proxy.$http.get(url);
  qcRuleList.push(...data.data);
}

// 获取左侧仪器表格数据
function findInstrItemTree() {
  instrItemTree.length = 0; //放入数据前清空数据
  expandedkeys.length = 0;
  treeLoading.value = true;
  const url = '/api/qc/qcInstrItem/findInstrAndInstrItemTree';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { seachValue: '', instrIds: searchForm.value.instrIds, poct: 1 }
    })
    .then((res: any) => {
      instrItemTree.push(...res.data);
      getExpandedkeys();
      if (instrItemTree.length > 0) {
        const sltObj = getChildren(instrItemTree[0]);
        handleClickType(sltObj);
        setCurTypeNode(sltObj); //定位当前行
      }
      treeLoading.value = false;
    })
    .catch((err: any) => {
      treeLoading.value = false;
      VxeMessage('获取左侧仪器表格数据异常', VxeNotifyType.error);
    });
}
//点击左侧树
function handleClickType(obj: any) {
  const isSearch = obj.isSearch;
  if (isSearch == '0') {
    sltInstrItem = obj;
    findInstrItemRuleList();
  } else {
    instrItemRuleList.length = 0;
    sltInstrItem = reactive({});
  }

  //如果点击的当前行数据是父级，那就禁用质控品维护的按钮
  if (!sltInstrItem.id) {
    disabledTag.value = true;
  } else {
    //如果点击的当前行数据是子集，那就不需要禁用质控品维护的按钮
    disabledTag.value = false;
  }
}

// 获取children那条数据
function getChildren(obj: any) {
  const children = obj.children;
  return children[0];
}

// 光标定位在左侧仪器表格上
function setCurTypeNode(sltObj: any) {
  proxy.$nextTick(() => {
    const treeName = 'dataTreeRef';
    const tree: any = proxy.$refs[treeName];
    tree.setCurrentKey(sltObj.id);
  });
}

function findInstrItemRuleList() {
  rloading.value = true;
  instrItemRuleList.length = 0; //放入数据前清空数据
  const url = '/api/qc/qcInstrItemRule/findInstrItemRuleList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { pid: sltInstrItem.id }
    })
    .then((res: any) => {
      instrItemRuleList.push(...res.data);
      rloading.value = false;
    })
    .catch((err: any) => {
      rloading.value = false;
      VxeMessage('获取右侧质控项目表格数据异常', VxeNotifyType.error);
    });
}

function addInstrItemRule() {
  if (isEmpty(sltInstrItem)) {
    VxeMessage('请选择仪器或项目', VxeNotifyType.error);
  } else {
    const record: any = {
      id: '',
      pid: sltInstrItem.id,
      isAlarm: false,
      isOutControl: false,
      enableDate: moment().format('YYYY-MM-DD'),
      seq: instrItemRuleList.length + 1
    };
    if (sltInstrItem.type == 'instr') {
      record.ptype = '1';
    } else if (sltInstrItem.type == 'instrItem') {
      record.ptype = '2';
    }
    instrItemRuleList.push(record);
  }
}
async function saveInstrItemRuleList() {
  if (isEmpty(sltInstrItem)) {
    VxeMessage('请选择仪器或项目', VxeNotifyType.error);
  } else {
    let $Xtable = proxy.$refs.instrItemRuleTableRef;
    if ($Xtable) {
      // 表格实例表用该方法拿到有id的为修改
      const updateRecords = await $Xtable.getUpdateRecords().filter((p: any) => {
        return p.id && p.id !== '';
      });
      // 拿到数组中没有id的数据为新增
      const InsertRecords = instrItemRuleList.filter((e: any) => {
        return !e.id || e.id === '';
      });

      const sveOrupdateRules = [] as any[];
      updateRecords.forEach((e: any) => {
        const iIRule: any = {
          id: e.id,
          pid: e.pid,
          ptype: e.ptype,
          ruleType: e.ruleType,
          ruleIds: e.ruleIds,
          isAlarm: e.isAlarm,
          isOutControl: e.isOutControl,
          enableDate: e.enableDate,
          seq: e.seq
        };
        iIRule.enableDate = isEmpty(e.enableDate) ? '' : e.enableDate + ' 00:00:00';
        iIRule.stopDate = isEmpty(e.stopDate) ? '' : e.stopDate + ' 23:59:59';

        sveOrupdateRules.push(iIRule);
      });
      InsertRecords.forEach((e: any) => {
        const iIRule: any = {
          id: e.id,
          pid: e.pid,
          ptype: e.ptype,
          ruleType: e.ruleType,
          ruleIds: e.ruleIds,
          isAlarm: e.isAlarm,
          isOutControl: e.isOutControl,
          enableDate: e.enableDate,
          seq: e.seq
        };
        iIRule.enableDate = isEmpty(e.enableDate) ? '' : e.enableDate + ' 00:00:00';
        iIRule.stopDate = isEmpty(e.stopDate) ? '' : e.stopDate + ' 23:59:59';
        sveOrupdateRules.push(iIRule);
      });

      if (sveOrupdateRules.length > 0) {
        const url = '/api/qc/qcInstrItemRule/saveOrUpdateInstrItemRule';
        const obj: any = {};
        obj.instrItemRuleList = sveOrupdateRules;
        proxy.$http
          .post(url, obj)
          .then((res: any) => {
            VxeMessage('更新成功', VxeNotifyType.success);
            setTimeout(() => {
              findInstrItemRuleList();
            }, 500);
          })
          .catch((err: any) => {
            VxeMessage('更新失败', VxeNotifyType.success);
          });
      } else {
        VxeMessage('无添加或修改数据', VxeNotifyType.error);
      }
    } else {
      return;
    }
  }
}

function deleteInstrItemRule() {
  const sltInstrItemRules = (proxy.$refs.instrItemRuleTableRef as any).getCheckboxRecords();
  if (!(sltInstrItemRules.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        //后台删除数据
        const delInstrItemRuleList = sltInstrItemRules.filter((p: any) => !isEmpty(p.id));
        if (delInstrItemRuleList.length > 0) {
          const data = { instrItemRuleList: delInstrItemRuleList };
          const url = '/api/qc/qcInstrItemRule/batchDeleteInstrItemRuleList';
          proxy.$http
            .post(url, data)
            .then((res: any) => {
              findInstrItemRuleList(); // 获取检验仪器表格数据
              VxeMessage(res.status.msg, VxeNotifyType.success);
            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        }
        //页面删除未保存的数据
        const removeInstrItemRuleList = sltInstrItemRules.filter((p: any) => isEmpty(p.id));
        if (removeInstrItemRuleList.length > 0) {
          // 删除的新增的空白数据 不走接口
          let $Xtable = proxy.$refs.instrItemRuleTableRef;
          if ($Xtable) {
            for (const removeRow of removeInstrItemRuleList) {
              await $Xtable.remove(removeRow);
              instrItemRuleList.splice(removeRow.seq - 1);
            }
          }
        }
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

function formatRuleType(row) {
  const item = qcRuleTypeList.find((item) => item.code === row.ruleType);
  return item ? item.name : row.ruleType;
}

function formatRuleNameByIds(row) {
  if (!isEmpty(row.ruleIds)) {
    const ruleNames: any = [];
    const ruelIdList = row.ruleIds.split(',');
    for (const ruelId of ruelIdList) {
      const item = qcRuleList.find((item) => item.id === ruelId);
      if (!isEmpty(item)) {
        ruleNames.push(item.name);
      }
    }
    return ruleNames.join(',');
  } else {
    return '';
  }

  // qcRuleList.filter(p=>p.isVisiable)

  // const obj = materialItemList.filter((p: any) => {
  //   defaultSelecteRowKeys.push(p.qcItemId);
  //   return p.qcItemId == row.id;
  // });
}

// 组件选中事件
function selectRow(row, index) {
  const nameArr = [];
  const idArr = [];
  row.forEach((item) => {
    nameArr.push(item.name);
    idArr.push(item.id);
  });
  const nameString = nameArr.join(',');
  const idString = idArr.join(',');
  // instrItemRuleList[index].name = nameString;
  instrItemRuleList[index].ruleIds = idString;
}
// 点击表当前行
function ruleRowClick({ row }) {
  if (isEmpty(row)) {
    sltInstrItemRule = {};
  } else {
    (proxy.$refs.instrItemRuleTableRef as any).setCurrentRow(row);
    sltInstrItemRule = row;
  }
}
function getExpandedkeys() {
  for (const materialItem of instrItemTree) {
    pusExpandedkeys(materialItem);
  }
}

function pusExpandedkeys(obj: any) {
  const children = obj.children;
  if (obj.type == 'instrClass') {
    //expandedkeys.push(obj.id);
  }
  if (!isEmpty(children) && children.length > 0) {
    for (const ch of children) {
      pusExpandedkeys(ch);
    }
  }
}
</script>

<style lang="scss" scoped>
#qcInstrItemRuleDiv {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .splitpanes {
      background-color: $base-white;
    }
    // 附加按钮间距
    .button-blue,
    .button-red {
      margin: 5px 0 5px 5px;
    }

    //右侧质控项目表格
    .tableBox {
      height: calc(100% - 40px);
    }

    // 弹框
    .el-dialog {
      font-weight: 700;
      max-height: 1000px;

      .dialog-footer {
        height: 40px;
      }
    }
  }
}
</style>
